# apps/app01/views/cart_views.py

from rest_framework import views, status
from rest_framework.response import Response
# from rest_framework.permissions import IsAuthenticated  # 如需可启用

from apps.app01.models import Cart, User


class CartListView(views.APIView):

    # permission_classes = [IsAuthenticated]  # 若需登录校验可启用

    def get(self, request):
        # 1. 获取当前登录用户
        user_id = request.user['user_id']
        user = User.objects.get(id=user_id)
        # user = User.objects.first()  # 测试时可写死

        # if user.is_anonymous:
        #     return Response(
        #         {"data": []},
        #         status=status.HTTP_401_UNAUTHORIZED
        #     )

        # 2. 查询当前用户的购物车商品
        cart_items = Cart.objects.filter(user=user_id)

        # 3. 组装返回数据
        data_list = []
        for item in cart_items:
            product_obj = item.product  # 获取Product对象

            # 如果有商品图片，拼接URL；根据你的MEDIA配置获取正确URL
            # 若是本地测试，pic_url.url 可能是 "/media/products/xxx.png"
            # 若是线上环境，需要完整域名+路径
            if not product_obj.pic_url:
                pic_url = '/default.png'
            else:
                pic_url = product_obj.pic_url.name

            # 组装单个商品的JSON
            data_list.append({
                "productId": product_obj.id,
                "picUrl": pic_url,
                "name": product_obj.name,
                "price": product_obj.price,
                "count": item.count,
                "selected": False,  # 购物车商品是否被勾选，可根据需求定义，这里默认 False
                "config": item.selected_configs,  # 直接返回 JSONField 中的配置
                "code": 1,
                "message": "ok"
            })

        # 4. 返回响应
        return Response({"data": data_list}, status=status.HTTP_200_OK)